package com.zhaozhaonews.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaozhaonews.file.service.FileStorageService;
import com.zhaozhaonews.model.common.dto.PageResponseResult;
import com.zhaozhaonews.model.common.dto.ResponseResult;
import com.zhaozhaonews.model.common.enums.AppHttpCodeEnum;
import com.zhaozhaonews.model.wemedia.dto.WmMaterialDto;
import com.zhaozhaonews.model.wemedia.entity.WmMaterial;
import com.zhaozhaonews.util.thread.WmThreadLocalUtil;
import com.zhaozhaonews.wemedia.mapper.WmMaterialMapper;
import com.zhaozhaonews.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author WanJL
 * @since 2025-02-17
 */
@Service
@Slf4j
@Transactional //启动spring事务管理
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;
    /**
     * 自媒体上传图片素材
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //1、上传图片素材到MinIO
        //1.1检查参数
        if (file==null||file.getSize()<=0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.2 上传
        //随机生成一个图片文件名
        String fileName = UUID.randomUUID().toString().replace("-","");
        //获取前端发送过来的图片的全名(文件名.扩展名)
        String originalFilename = file.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接文件全名fileName+postfix
        String fullName=fileName+postfix;
        String fileId=null;
        try {
            //调用FileStorageService执行上传
            fileId = fileStorageService.uploadImgFile("", fullName, file.getInputStream());
            log.info("上传图片到MinIO中，fileId--->{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl--文件上传失败");
        }

        //2、把素材信息存入数据库表
        //以上两步骤，必须同时成功，或同时失败--启动事务管理spring事务管理
        WmMaterial wmMaterial=new WmMaterial();
        //调用本地线程，获取当前操作的用户的ID
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        //保存到数据库
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材分页列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult list(WmMaterialDto dto) {
        //检查参数
        dto.checkParam();

        // MybatisPlus的分页插件---比较适合用在一些简单的分页业务。不适合复杂逻辑的分页
        IPage page=new Page(dto.getPage(),dto.getSize(),true);

        /*page = lambdaQuery()
                .eq(dto.getIsCollection() != null && dto.getIsCollection() == 1,
                        WmMaterial::getIsCollection, dto.getIsCollection())//是否收藏
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())//根据用户查询
                .orderByDesc(WmMaterial::getCreatedTime)//倒序
                .page(page);*/
        //方式二：拼接查询条件
        LambdaQueryWrapper<WmMaterial> lqw=new LambdaQueryWrapper<>();
        //判断是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1)
            lqw.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        //根据用户查询
        lqw.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //倒序
        lqw.orderByDesc(WmMaterial::getCreatedTime);



        //封装分页
        page=page(page, lqw);

        log.info("service--总条数--->{}",page.getTotal());

        //封装分页结果
        PageResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }
}
